package com.xzc.mapper;

import com.xzc.entity.Box;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * simulation database
 *
 * @auther kaka
 * @Date 2020-06-16
 */

@Service
public class BoxMapper implements InitializingBean {

    private Map<String, List<Box>> goods = new HashMap<>();

    //increment id
    public static AtomicInteger boxId = new AtomicInteger(1);

//    private Lock lock = new ReentrantLock();

    public int incrementId() {
//        Lock myLock = lock;
//        try {
//            myLock.lock();
//            boxId++;
//        } finally {
//            myLock.unlock();
//        }
        return boxId.getAndAdd(1);
    }

    @Override
    public void afterPropertiesSet() {
        Box box = new Box()
                .setBoxId(boxId.get())
                .setNums(100);
        List<Box> boxes = new ArrayList<>();
        boxes.add(box);
        goods.put("order1", boxes);
    }


    public void addBox(String orderId, Box box) {
        List<Box> boxList = getByOrderId(orderId);
        box.setBoxId(incrementId());
        boxList.add(box);
        goods.put(orderId, boxList);
    }

    public List<Box> getByOrderId(String orderId) {
        return goods.get(orderId);
    }

    public Box getBoxByBoxId(String orderId, int boxId) {
        List<Box> boxList = getByOrderId(orderId);
        for (Box box : boxList) {
            if (box.getBoxId() == boxId) {
                return box;
            }
        }
        return null;
    }

    public void delBox(String orderId, List<String> boxIds) {
        List<Box> boxList = getByOrderId(orderId);
        Iterator<Box> it = boxList.iterator();
        while (it.hasNext()) {
            Box box = it.next();
            for (String boxId : boxIds) {
                if (box.getBoxId() == Integer.parseInt(boxId)) {
                    it.remove();
                }
            }
        }
    }
}
